import 'package:flutter/material.dart';
import 'package:qunaimedical/components/colored_tabbar.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/category.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/news/news_list.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

/// 健康资讯
class NewsHomePage extends StatefulWidget {
  const NewsHomePage({Key key}) : super(key: key);

  @override
  _NewsHomePageState createState() => _NewsHomePageState();
}

class _NewsHomePageState extends State<NewsHomePage> {
  List<Category> _categories = [];

  @override
  void initState() {
    super.initState();
    _fetchCategories();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: _categories.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text('健康资讯'),
          bottom: ColoredTabBar(
            color: Colors.white,
            width: MediaQuery.of(context).size.width,
            tabBar: TabBar(
              isScrollable: true,
              labelColor: Theme.of(context).primaryColor,
              unselectedLabelColor: Colors.black54,
              labelPadding:
                  EdgeInsets.symmetric(vertical: 12.5, horizontal: 10),
              indicatorSize: TabBarIndicatorSize.label,
              indicator: UnderlineTabIndicator(
                  borderSide: BorderSide(
                      width: 2, color: Theme.of(context).primaryColor)),
              tabs: _categories.map((e) => Text(e.label)).toList(),
            ),
          ),
        ),
        body: TabBarView(
            children:
                _categories.map((e) => NewsListPage(category: e)).toList()),
      ),
    );
  }

  void _fetchCategories() async {
    var data = await XHttp.postJson(sprintf(Urls.DICT_VALUES, ['infoType']));
    if (data != null) {
      ListResponse response = ListResponse.fromJson(data);
      if (response.code == 1) {
        if (mounted) {
          setState(() {
            _categories =
                List.from(response.data.map((e) => Category.fromJson(e)));
            _categories.sort((a, b) => a.sort.compareTo(b.sort));
          });
        }
      }
    }
  }
}
